package com.education.wisdom.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.education.common.core.ServletUtils;
import com.education.common.utils.*;
import com.education.wisdom.pojo.*;
import com.education.wisdom.service.*;
import com.education.wisdom.vo.QuestionsVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.mockito.stubbing.Answer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.education.common.core.BaseController.writeJSON;


/**
 * 职业技能鉴定目录体系 信息操作处理
 *
 * @author ruoyi
 * @date 2019-06-19
 */
@Controller
@CrossOrigin
@Slf4j
@ResponseBody
@RequestMapping("/web/catalogAppraisal")
@Api(tags = {"职业技能鉴定板块"})
public class FullCatalogAppraisalController {

    @Autowired
    private ICatalogAppraisalService catalogAppraisalService;

    @Autowired
    private IPaperService paperService;

    @Autowired
    private IQuestionsService questionsService;

    @Autowired
    private IAnswersService answersService;

    @Autowired
    private JrAnswTwoService jrAnswTwoService;


    //查询答案
    @GetMapping("/answer")
    public ApiReturnObject answer(Answers answers) {
        List<Answers> answersList = answersService.selectAnswersList(answers);
        if (answersList.size() == 0){
             return new ApiReturnObject("201", "fail", "查无数据");
        }
        String[] split = answersList.get(0).getDjContent().split(",");
        List<JrAnswTwo> list = jrAnswTwoService.selectAnswIds(split);
        for (JrAnswTwo jrAnswTwo : list) {
            if ("3".equals(jrAnswTwo.getIsJD())) {
                String[] array = jrAnswTwo.getText().split(",");
                jrAnswTwo.setTextarray(array);
            }
        }
        answersList.get(0).setContArray(list);

        return new ApiReturnObject("200", "success", answersList.get(0));
    }

    @GetMapping("/list")
    public void list(HttpServletResponse response) throws IOException {
        log.info(LogUtil.LogInfo("查询职业技能鉴定目录体系", new Date()));
        List<CatalogAppraisal> catalogAppraisals = catalogAppraisalService.selectCatalogAppraisalList(null);
        writeJSON(catalogAppraisals, response, "200", "success");
    }

    @GetMapping("/queryPaper")
    public void queryPaper(HttpServletResponse response, Integer pageSize, Integer pageNum, Integer appraisalCatalogId) throws IOException {
        log.info(LogUtil.LogInfo("查询职业技能鉴定目录对应试题", new Date()));
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        if (appraisalCatalogId != null) {
            List<Paper> paperList = paperService.selectByAppraisalCatalogId(appraisalCatalogId);
            writeJSON(new PageInfo<>(paperList), response, "200", "success");
        } else {
            List<Paper> paperList = paperService.selectTitlelist();
            writeJSON(new PageInfo<>(paperList), response, "200", "success");
        }
    }

    @GetMapping("/questionsListPeople")
    public void questionsListPeople(HttpServletResponse response, String paperId,String userId) throws Exception {
        log.info(LogUtil.LogInfo("查询试题列表", new Date()));
        String ipAddr = IpUtils.getIpAddr(ServletUtils.getRequest());//获取当前电脑ip地址
        Map<String, Object> map = new HashMap<>();
        map.put("paperId", paperId);
        List<QuestionsVo> list = questionsService.selectQuestionsListById(map);
        int count = questionsService.selectCount(map);
        //查询试卷
        Paper paper = paperService.selectPaperById(Integer.parseInt(paperId));
        Map<String, Object> map1 = new HashMap<>();
        map1.put("count", count);
        map1.put("list", list);
        if (StringUtils.isNotNull(paper.getStartTime()))paper.setStartTimeStr(DateUtil.format(paper.getStartTime()));
        if (StringUtils.isNotNull(paper.getEndTime()))paper.setEndTimeStr(DateUtil.format(paper.getEndTime()));
        map1.put("name",paper);
        writeJSON(map1, response, "200", "成功");
    }

    @GetMapping("/questionsList")
    public void questionsList(HttpServletResponse response, String paperId,String userId) throws Exception {
        log.info(LogUtil.LogInfo("查询试题列表", new Date()));
        String ipAddr = IpUtils.getIpAddr(ServletUtils.getRequest());//获取当前电脑ip地址
        log.info("ip地址 : {}",ipAddr);
        Map<String, Object> map = new HashMap<>();
        map.put("paperId", paperId);
        List<QuestionsVo> list = questionsService.selectQuestionsListById(map);

        int count = 0;
        //先判断中间表中是否存在数据
        Integer integer = questionsService.selectCountByPaperId(Integer.valueOf(paperId));
        if(integer > 0){
            count = questionsService.selectCount(map);
        }
        //查询试卷
        Paper paper = paperService.selectPaperById(Integer.parseInt(paperId));
/*        if (StringUtil.isNotEmpty(paper.getIp())){
            String[] split = paper.getIp().split("-");//试卷ip范围
            if (!IpUtils.ipIsValid(split[0], split[1],ipAddr)){
                writeJSON("当前电脑ip不在试卷指定范围内", response, "201", "失败" + ipAddr);
            }
        }
        if (paper.getStartTime() != null){
            if (!DateUtil.isFlag(new Date(),paper.getStartTime())){
                writeJSON("未到试卷开始考试时间", response, "201", "失败");
            }
        }
        if (paper.getEndTime() != null){
            if (DateUtil.isFlag(new Date(),paper.getEndTime())){
                writeJSON("考试时间已结束", response, "201", "失败");
            }
        }*/
        //查询该用户是否已经答题
        Answers answers = new Answers();
        answers.setDjPaperid(Integer.parseInt(paperId));
        answers.setDjUserid(userId);
        List<Answers> answersList = answersService.selectAnswersList(answers);
        if (StringUtils.isNotEmpty(answersList)){
            if ("0".equals(paper.getRtype())){
                writeJSON("考生已答题 不可重新考试", response, "201", "失败");
            }
        }
        Map<String, Object> map1 = new HashMap<>();
        map1.put("count", count);
        map1.put("list", list);
//        paper.setStartTimeStr(DateUtil.format(paper.getStartTime()));
//        paper.setEndTimeStr(DateUtil.format(paper.getEndTime()));
        map1.put("name",paper);
        writeJSON(map1, response, "200", "成功");
    }

    /**
     * 用户试卷答题
     */
    @GetMapping("/answers")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "djPaperid", value = "试卷编号", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "djUserid", value = "答题者Id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "djQuestionsids", value = "答题ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "djAnswers", value = "答题内容", required = true, dataType = "String"),
            @ApiImplicitParam(name = "djStarttime", value = "开始时间", required = true, dataType = "Date")})
    public void answers(HttpServletResponse response,
                        Integer djPaperid,
                        String djUserid,
                        String djAnswers,
                        String djStarttime) throws Exception {
        BigDecimal b0 = new BigDecimal(0);
        Paper paper = paperService.selectPaperById(djPaperid);
        if (paper != null) {
            List<JrAnswTwo> twoList = JSONObject.parseArray(djAnswers, JrAnswTwo.class);
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder str = null;
            for (JrAnswTwo jrAnswTwo : twoList) {
                JrAnswTwo answTwo = new JrAnswTwo();
                answTwo.setText(jrAnswTwo.getText());
                answTwo.setIsJD(jrAnswTwo.getIsJD());
                jrAnswTwoService.insertJrAnswTwo(answTwo);
                str = stringBuilder.append(answTwo.getId()).append(",");
                //1 单选 2 判断 3 多选 4 简答
                Questions question = questionsService.selectQuestionsById(jrAnswTwo.getId().toString());
                String stAnswer = question.getStAnswer();//正确答案
                if ("4".equals(question.getQuestionType())) continue;
                if ("3".equals(question.getQuestionType())){
                    String[] one = jrAnswTwo.getText().split(",");//考试答案
                    String[] two = stAnswer.split(",");//正确答案
                    List<String> list = Arrays.asList(two);
//                    if (one.length != two.length) continue;
                    for (int i = 0; i < one.length; i++) {
                        if (list.contains(one[i])){
                            String s = StringUtil.isEmpty(paper.getManyScore()) ? "0" : paper.getManyScore();
                            b0 = b0.add(new BigDecimal(s));
                        }
                    }
                    continue;
                }
                if ("2".equals(question.getQuestionType())){
                    String one = jrAnswTwo.getText();//考试答案
                    String two = stAnswer;//正确答案
                    if (StringUtils.isNotEmpty(one) && one.equals(two)) {
                        String s = StringUtil.isEmpty(paper.getJudgmentScore()) ? "0" : paper.getJudgmentScore();
                        b0 = b0.add(new BigDecimal(s));
                    }
                    continue;
                }
                if ("1".equals(question.getQuestionType())){
                    String one = jrAnswTwo.getText();//考试答案
                    String two = stAnswer;//正确答案
                    if (StringUtils.isNotEmpty(one) && one.equals(two)) {
                        String s = StringUtil.isEmpty(paper.getSingleScore()) ? "0" : paper.getSingleScore();
                        b0 = b0.add(new BigDecimal(s));
                    }
                    continue;
                }
            }
            Answers answer = new Answers();
            answer.setDjId(UUIDUtils.getByUUId());
            answer.setDjEndtime(new Date());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date strtodate = formatter.parse(djStarttime);
            answer.setDjStarttime(strtodate);
            String s = str.toString();
            answer.setDjContent(s.substring(0,s.length() - 1));
            answer.setDjPaperid(djPaperid);
            answer.setDjScore(b0);
            answer.setDjUserid(djUserid);
            answersService.insertAnswers(answer);
        }
        writeJSON(b0, response, "200", "成功");
    }

//    /**
//     * 用户试卷答题
//     */
//    @GetMapping("/answers")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "djPaperid", value = "试卷编号", required = true, dataType = "Integer"),
//            @ApiImplicitParam(name = "djUserid", value = "答题者Id", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "djQuestionsids", value = "答题ID", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "djAnswers", value = "答题内容", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "djStarttime", value = "开始时间", required = true, dataType = "Date")})
//    public void answers(HttpServletResponse response, Integer djPaperid, String djUserid, String djQuestionsids, String djAnswers,
//                        String djStarttime) throws Exception {
//        log.info(LogUtil.LogInfo("试卷答题", new Date()));
//        BigDecimal b0 = new BigDecimal(0);
//        Paper paper = paperService.selectPaperById(djPaperid);
//        if (paper != null) {
//            String[] questionsids = djQuestionsids.split(",");//试题id
//            String[] sanswers = djAnswers.split(",");
//            if (questionsids.length == sanswers.length) {
//                //根据试题id查询试题  进行比较答案是否正确
//                for (int i = 0; i < questionsids.length; i++) {
//                    String questionsid = questionsids[i];
//                    String sanswer1 = sanswers[i];
//                    Questions question = questionsService.selectQuestionsById(questionsid);
//                    if ("4".equals(question.getQuestionType())) continue;
//                    String stAnswer = question.getStAnswer();//答案
//                    BigDecimal stScore = question.getStScore();//分数
//                    if (stAnswer.equals(sanswer1)) {//答案正确
//                        b0 = b0.add(stScore);//分数
//                    }
//                }
//                Answers answer = new Answers();
//                answer.setDjId(UUIDUtils.getByUUId());
//                answer.setDjEndtime(new Date());
//                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date strtodate = formatter.parse(djStarttime);
//                answer.setDjStarttime(strtodate);
//                answer.setDjContent(djAnswers);
//                answer.setDjPaperid(djPaperid);
//                answer.setDjScore(b0);
//                answer.setDjUserid(djUserid);
//                answersService.insertAnswers(answer);
//            }
//        }
//        writeJSON(b0, response, "200", "成功");
//    }

    @GetMapping("/search")
    public void search(HttpServletResponse response, String sjIntroduction, String appraisalCatalogId, Integer pageSize, Integer pageNum) throws IOException {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<Paper> list = paperService.selectByLike(sjIntroduction,appraisalCatalogId);
        writeJSON(new PageInfo<>(list), response, "200", "成功");
    }


}
